package com.gzx.plugin.tjzy.modular.phone.error.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gzx.plugin.tjzy.modular.phone.dto.GzxPhoneStatusDto;
import com.gzx.plugin.tjzy.modular.phone.error.entity.GzxErrorPhone;
import com.gzx.plugin.tjzy.modular.phone.error.mapper.GzxErrorPhoneMapper;
import com.gzx.plugin.tjzy.modular.phone.error.service.GzxErrorPhoneDbService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.util.CommonCryptogramUtil;
import vip.xiaonuo.common.util.CommonDateUtil;
import vip.xiaonuo.common.util.CommonSleepUtil;

import java.util.List;
import java.util.stream.Collectors;

import static org.apache.commons.lang.StringEscapeUtils.escapeSql;

/**
 * @author zjt
 * @description
 * @date 2025/6/11 09:21
 */
@Service
@RequiredArgsConstructor
public class GzxErrorPhoneDbServiceImpl implements GzxErrorPhoneDbService {

    private final GzxErrorPhoneMapper errorPhoneMapper;

    /**
     * 查询异常手机号
     *
     * @param lambdaQueryWrapper
     * @return
     */
    @Override
    @DS("tjzy-async")
    public List<GzxErrorPhone> selectList(LambdaQueryWrapper<GzxErrorPhone> lambdaQueryWrapper) {
        return errorPhoneMapper.selectList(lambdaQueryWrapper);
    }

    /**
     * 批量保存到数据库
     *
     * @param phoneStatusDtoList
     */
    @Override
    @DS("tjzy-async")
    public void saveBatch(List<GzxPhoneStatusDto> phoneStatusDtoList, String userId, String tenantId) {
        String todayStr = CommonDateUtil.getCurrentMonth();
        String currentTime = CommonDateUtil.getCurrentTimeStr();
        String batchSql = phoneStatusDtoList.stream()
                .map(s -> String.format("('%s', %s,  %s, %s, '%s','%s', '%s', '%s')",
                        escapeSql(CommonCryptogramUtil.doSm1AesEncrypt(s.getPhone())),
                        escapeSql(String.valueOf(s.getType())),
                        escapeSql("1"),
                        escapeSql(todayStr),
                        escapeSql(s.getAllJson()),
                        escapeSql(currentTime),
                        escapeSql(tenantId),
                        escapeSql(userId)))
                .collect(Collectors.joining(", ")).replace("'null'", "null");
        errorPhoneMapper.insertBatchSql(batchSql);
        CommonSleepUtil.sleep100();
    }
}
